package com.powernode.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.powernode.config.AliyunOSSConfig;
import com.powernode.ex.handler.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;

/**
 * 文件上传控制层
 */
@Api(tags = "文件上传接口管理")
@RequestMapping("xxx")
@RestController
public class FileUploadController {

    @Resource
    private AliyunOSSConfig aliyunOSSConfig;

    /**
     * 上传文件：
     * 1.接口要求请求方式必须是Post
     * 2.接收文件对象的类型是：MultipartFile ,该对象有springMVC提供
     * @return 与前端约好返回图像的url地址
     */
    @ApiOperation("上传单个文件")
    @GetMapping("upload/element")
    public String uploadFile(MultipartFile file) throws com.aliyuncs.exceptions.ClientException {

        //1. 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        //2. 填写Bucket名称
        String bucketName = aliyunOSSConfig.getBucketName();
        //3. 以天为单位的名称，作为文件夹名称
        String newFoldername = DateUtil.format(new Date(), "yyyy-MM-dd");
        //4. 以时间戳为新文件名
        String fileName = DateUtil.format(new Date(), "HHmmssSSS");
        //5. 获取原文件的后缀
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = newFoldername + fileName + fileSuffix;

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliyunOSSConfig.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .build();

        URL url = null;
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,file.getInputStream());

            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            //创建上传文件访问的url地址
            url = ossClient.generatePresignedUrl( bucketName, objectName, DateUtil.offsetDay(new Date(),365*20));
        } catch (Exception oe) {

            System.out.println("Error Message:" + oe.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        if (url == null){
            throw new BusinessException("图片路径url为null");
        }
        return url.toString();
    }
}

